package com.ycy.leetcode.find;

import org.junit.Test;

public class BinarySearch {

  /**
   * 二分查找
   */
  @Test
  public void test() {

    binarySearch(13);
    binarySearch(14);

  }

  public void binarySearch(int target) {
    int[] arr = {0, 2, 13};

    int low = 0;
    int high = arr.length - 1;

    while (true) {
      if (low > high) {
        System.out.println(-1);
        break;
      }
      int mid = (low + high) / 2; //偏左
      int midval = arr[mid];

      if (midval > target) {
        high = mid-1;
      } else if (midval < target) {
        low = mid + 1;  //这个地方+1 很久讲究
      } else {
        //查到了
        System.out.println(mid);
        break;
      }

    }

  }

}
